package com.bwie.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.domain.TbOrder;
import com.bwie.domain.TbUser;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.service.IUserService;
import com.bwie.state.PayStateEnum;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class OrderPayTask implements Job {

    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    IUserService iUserService;

    /**
     * 订单30分钟没有支付，则取消订单
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 取出所有没有支付的订单
        List<TbOrder> tbOrders = tbOrderMapper.selectList(
                new QueryWrapper<TbOrder>().lambda().eq(TbOrder::getOrderStatus, PayStateEnum.UNPAID.getCode())
        );

        // 遍历，判断是否超时
        for (TbOrder tbOrder : tbOrders) {
            long currentTime = System.currentTimeMillis();
            long lTime = tbOrder.getCreateTime().getTime();
            long minutes = (currentTime - lTime) / 1000 / 60;
            if(minutes > 30) {
                // 取消订单
                tbOrder.setOrderStatus(PayStateEnum.CANCEL.getCode());
                tbOrderMapper.updateById(tbOrder);

                // 发送订已被取消的消息给用户
                Integer userId = tbOrder.getUserId();
                R r = iUserService.getUserById(userId);
                if(r.getCode() == 200) {
                    // 获取R类的data中获取user对象
                    String s = JSON.toJSONString(r.getData());
                    TbUser tbUser = JSON.parseObject(s, TbUser.class);
                    log.info(tbUser.toString());
                    Boolean ok = MobileMessageUtil.sendMobileMessage(tbUser.getUserMobile(), "订单已取消");
                    if(!ok) {
                        log.info("发送短信失败，使用邮件继续通知");
                        // TODO
                    }
                }
                else {
                    log.info("用户不存在，无法发送通知");
                }

            }
        }

        log.info("检查超时未支付的订单~~~~~~~~~~~~~~");
    }
}
